<template>
  <div class="register-modal-content">
    <el-form
      ref="registerFormRef"
      :model="registerForm"
      :rules="registerRules"
      label-width="80px"
      @submit.prevent="handleRegister"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="registerForm.username"
          placeholder="请输入用户名"
          :prefix-icon="UserIcon"
        />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="registerForm.email"
          type="email"
          placeholder="请输入邮箱"
          :prefix-icon="Message"
        />
      </el-form-item>

      <el-form-item label="姓名" prop="full_name">
        <el-input
          v-model="registerForm.full_name"
          placeholder="请输入真实姓名"
          :prefix-icon="UserFilled"
        />
      </el-form-item>

      <el-form-item label="家庭名称" prop="family_name">
        <el-input
          v-model="registerForm.family_name"
          placeholder="请输入家庭名称"
          :prefix-icon="HomeFilled"
        />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="请输入密码（至少6位）"
          :prefix-icon="Lock"
          show-password
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
          :prefix-icon="Lock"
          show-password
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :loading="isLoading"
          @click="handleRegister"
          style="width: 100%"
        >
          {{ isLoading ? "注册中..." : "注册" }}
        </el-button>
      </el-form-item>

      <el-form-item v-if="registerError">
        <el-alert
          :title="registerError"
          type="error"
          :closable="false"
          show-icon
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { useAuthStore } from "@/stores/auth";
import { authApi, handleAuthError } from "@/services/authService";
import type { RegisterForm, User } from "@/types/auth";
import type { FormInstance, FormRules } from "element-plus";
import { User as UserIcon, Lock, Message, UserFilled, HomeFilled } from "@element-plus/icons-vue";

// 定义组件属性和事件
defineProps<{
  visible: boolean;
}>();

const emit = defineEmits<{
  close: [];
  "register-success": [user: User];
}>();

// 获取认证状态管理器
const authStore = useAuthStore();

// 响应式状态
const isLoading = computed(() => authStore.isLoading);
const registerError = ref<string>("");

// 表单引用
const registerFormRef = ref<FormInstance>();

// 表单数据
const registerForm = reactive<RegisterForm>({
  username: "",
  email: "",
  password: "",
  confirmPassword: "",
  full_name: "",
  family_name: "",
});

// Element UI 表单验证规则
const registerRules: FormRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度在 3 到 20 个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  full_name: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度在 2 到 20 个字符", trigger: "blur" },
  ],
  family_name: [
    { required: true, message: "请输入家庭名称", trigger: "blur" },
    { min: 2, max: 20, message: "家庭名称长度在 2 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 清除错误信息
const clearErrors = () => {
  authStore.clearError();
  registerError.value = "";
};

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return;

  try {
    await registerFormRef.value.validate();
    
    clearErrors();

    // 注册逻辑
    const response = await authApi.register({
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      full_name: registerForm.full_name,
      family_name: registerForm.family_name,
    });

    // 触发成功事件
    emit("register-success", response);

    // 关闭模态框
    emit("close");

    // 重置表单
    resetRegisterForm();
  } catch (error: unknown) {
    registerError.value = handleAuthError(error);
  }
};

// 重置表单
const resetRegisterForm = () => {
  registerForm.username = "";
  registerForm.email = "";
  registerForm.password = "";
  registerForm.confirmPassword = "";
  registerForm.full_name = "";
  registerForm.family_name = "";
};
</script>

<style lang="scss" scoped>
@use "../styles/variables" as *;
@use "../styles/mixins" as *;

.register-modal-content {
  padding: 20px;
}

// Element UI 样式覆盖
:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--text-primary);
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px var(--theme-primary);
}

:deep(.el-button--primary) {
  background-color: var(--theme-primary);
  border-color: var(--theme-primary);
  
  &:hover {
    background-color: var(--theme-primary);
    border-color: var(--theme-primary);
    opacity: 0.9;
  }
}

:deep(.el-alert) {
  border-radius: 8px;
}
</style>